import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { judgeApi, contestantApi, scoreApi } from '@/api'
import type { Judge, Contestant, ScoreResponse } from '@/types'

export const useScoringStore = defineStore('scoring', () => {
  // 状态
  const judges = ref<Judge[]>([])
  const contestants = ref<Contestant[]>([])
  const scores = ref<ScoreResponse[]>([])
  const lastUpdateTime = ref<Date>(new Date())

  // 计算属性
  const averageScore = computed(() => {
    if (scores.value.length < 3) return 0
    const sortedScores = [...scores.value].map(s => s.score).sort((a, b) => a - b)
    const trimmedScores = sortedScores.slice(1, -1) // 去掉最低分和最高分
    return trimmedScores.length > 0 ? trimmedScores.reduce((sum, score) => sum + score, 0) / trimmedScores.length : 0
  })

  const maxScore = computed(() => scores.value.length ? Math.max(...scores.value.map(s => s.score)) : 0)
  const minScore = computed(() => scores.value.length ? Math.min(...scores.value.map(s => s.score)) : 0)

  // 动作
  async function loadJudges() {
    try {
      judges.value = await judgeApi.getAll()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('加载评委列表失败:', error)
      throw error
    }
  }

  async function loadContestants() {
    try {
      contestants.value = await contestantApi.getAll()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('加载选手列表失败:', error)
      throw error
    }
  }

  async function loadScores(contestantId: number) {
    try {
      scores.value = await scoreApi.getByContestant(contestantId)
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('加载评分失败:', error)
      throw error
    }
  }

  async function createScore(scoreData: { judge_id: number; contestant_id: number; score: number }) {
    try {
      await scoreApi.create(scoreData)
      // 重新加载相关数据
      await loadJudges()
      await loadContestants()
      if (scores.value.length > 0) {
        await loadScores(scoreData.contestant_id)
      }
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('创建评分失败:', error)
      throw error
    }
  }

  async function clearJudgeScore(judgeName: string, contestantId: number) {
    try {
      await scoreApi.clearJudgeScoreByName(judgeName, contestantId)
      // 重新加载评分数据
      await loadScores(contestantId)
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('清空评分失败:', error)
      throw error
    }
  }

  async function createJudge(judgeData: { name: string }) {
    try {
      await judgeApi.create(judgeData)
      await loadJudges()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('创建评委失败:', error)
      throw error
    }
  }

  async function createContestant(contestantData: { number: string; name: string }) {
    try {
      await contestantApi.create(contestantData)
      await loadContestants()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('创建选手失败:', error)
      throw error
    }
  }

  async function activateContestant(contestantId: number) {
    try {
      await contestantApi.activate(contestantId)
      await loadContestants()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('激活选手失败:', error)
      throw error
    }
  }

  async function deleteJudge(judgeId: number) {
    try {
      await judgeApi.delete(judgeId)
      await loadJudges()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('删除评委失败:', error)
      throw error
    }
  }

  async function deleteContestant(contestantId: number) {
    try {
      await contestantApi.delete(contestantId)
      await loadContestants()
      lastUpdateTime.value = new Date()
    } catch (error) {
      console.error('删除选手失败:', error)
      throw error
    }
  }

  // 初始化数据
  async function initialize() {
    await Promise.all([loadJudges(), loadContestants()])
  }

  return {
    // 状态
    judges,
    contestants,
    scores,
    lastUpdateTime,
    // 计算属性
    averageScore,
    maxScore,
    minScore,
    // 动作
    loadJudges,
    loadContestants,
    loadScores,
    createScore,
    clearJudgeScore,
    createJudge,
    createContestant,
    activateContestant,
    deleteJudge,
    deleteContestant,
    initialize
  }
})
